'use client';

import { useEffect, useState } from 'react';

interface ThemeProviderProps {
  children: React.ReactNode;
}

export default function ThemeProvider({ children }: ThemeProviderProps) {
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
    
    // 初始化主题
    const initTheme = () => {
      const savedTheme = localStorage.getItem('theme');
      const prefersColorScheme = window.matchMedia('(prefers-color-scheme: dark)');
      const systemPrefersDark = prefersColorScheme.matches;

      let isDark = false;
      if (savedTheme === 'light') {
        isDark = false;
      } else if (savedTheme === 'dark') {
        isDark = true;
      } else {
        isDark = systemPrefersDark;
        localStorage.setItem('theme', isDark ? 'dark' : 'light');
      }

      updateDOMTheme(isDark);
    };

    const updateDOMTheme = (isDark: boolean) => {
      if (isDark) {
        document.documentElement.classList.add('dark');
        document.body.style.backgroundColor = '#000000';
        document.body.style.color = '#ffffff';
      } else {
        document.documentElement.classList.remove('dark');
        document.body.style.backgroundColor = '#ffffff';
        document.body.style.color = '#000000';
      }
    };

    // 监听主题变化事件
    const handleThemeChange = (e: CustomEvent) => {
      const newTheme = e.detail.theme;
      updateDOMTheme(newTheme === 'dark');
    };

    // 初始化主题
    initTheme();

    // 监听主题变化
    window.addEventListener('themeChange', handleThemeChange as EventListener);

    return () => {
      window.removeEventListener('themeChange', handleThemeChange as EventListener);
    };
  }, []);

  // 防止服务器端渲染的闪烁
  if (!mounted) {
    return <div className="opacity-0">{children}</div>;
  }

  return <>{children}</>;
} 